<?php

namespace App\Models;

use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Facades\DB;

/*区域model*/

class NavigationArea extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';


    protected $table = 'navigation_area';

    protected $guarded = []; //使用模型  update 更新时，允许被全部更新，若不写，则会报错 或 没任何数据变化

    /*关联点位表*/
    public function conPoint()
    {
        return $this->hasMany(NavigationPoint::class, 'area_id', 'id');
    }
    /*关联区域索书号分类表*/
    public function conBookNum()
    {
        return $this->hasMany(NavigationAreaBookNum::class, 'area_id', 'id');
    }
    /**
     * 筛选列表
     * @param build_id int 所属建筑id
     * @param except_id int  要排除的id。选择过渡区域使用
     * @param area_id int  区域id
     * @param is_play int  是否显示
     */
    public function filterList($build_id, $except_id = null, $area_id = null,$is_play = null)
    {
        $res = $this->select('id', 'name', 'alias_name', 'img', 'is_start', 'sort','rotation_angle')->where('is_del', 1)
            ->where(function ($query) use ($except_id, $area_id,$is_play) {
                if ($except_id) {
                    $query->where('id', '<>', $except_id);
                }
                if ($area_id) {
                    $query->where('id', $area_id);
                }
                if ($is_play) {
                    $query->where('is_play', $is_play);
                }
            })
            ->where('build_id', $build_id)
            ->orderByDesc('sort')
            ->orderBy('id')
            ->get()
            ->toArray();
        return $res;
    }

    /**
     * 列表
     * @param build_id int 所属建筑id
     * @param limit int 分页大小
     * @param level_id int 区域等级 1一级区域 2有索书号的区域 默认查所有
     * @param keywords string 搜索关键词
     */
    public function lists($build_id, $level_id, $keywords, $limit)
    {
        $res = $this->select('id', 'name', 'alias_name', 'img', 'is_start', 'is_play', 'level','rotation_angle')
            ->with('conPoint', function ($query) {
                $query->select('id', 'area_id', 'name', 'type', 'line', 'transtion_area_id')
                    ->orderBy('type')
                    ->orderBy('create_time')
                    ->where('is_del', 1);
            })
            ->where(function ($query) use ($keywords) {
                if ($keywords) {
                    $query->where('name', 'like', "%$keywords%")->orWhere('alias_name', 'like', "%$keywords%");
                }
            })
            ->where(function ($query) use ($level_id) {
                if ($level_id) {
                    $query->where('level_id', $level_id);
                }
            })
            ->where('is_del', 1)
            ->where('build_id', $build_id)
            ->orderByDesc('sort')
            ->orderBy('id')
            ->paginate($limit)
            ->toArray();

        //根据是否传有图片确认是否上传路径图
        foreach ($res['data'] as $key => $val) {
            $res['data'][$key]['is_img'] = !empty($val['img']) ? 1 : 2; //1有传图 2没传图
            $area_classify = "";
            if (!empty($val['con_book_num'])) {
                foreach ($val['con_book_num'] as $k => $v) {
                    $area_classify .= ',' . $v['classify'];
                }
            }
            $res['data'][$key]['classify'] = trim($area_classify, ',');
            unset($res['data'][$key]['con_book_num']);
            if (!empty($val['con_point'])) {
                $transtion_area_name = "";
                foreach ($val['con_point'] as $k => $v) {
                    if ($v['type'] == 1 || $v['type'] == 4) {
                        $cur_is_img = 3; //不提示任何信息
                    } else {
                        $cur_is_img = !empty($v['line']) ? 1 : 2;
                    }
                    $v['is_img'] = $cur_is_img;
                    //查询关联点位名称
                    if (in_array($v['type'], [3, 4]) && !empty($v['transtion_area_id'])) {
                        //查询过渡区域
                        $transtion_area_data = explode(',', $v['transtion_area_id']);
                        $transtion_area_name = $this->where('is_del', 1)->whereIn('id', $transtion_area_data)->pluck('name')->toArray();
                        $transtion_area_name = !empty($transtion_area_name) ? implode(',', $transtion_area_name) : '';
                    }
                    $v['transtion_area_name'] = $transtion_area_name;
                    unset($v['line'], $v['transtion_area_id']);
                    $res['data'][$key]['con_point'][$k] = $v;
                }
            }
        }

        return $res;
    }
    /**
     * 检查svg图片格式是否正确*
     * @param $img string 图片相对路径
     */
    public function checkSvgImg($img)
    {
        $uploads_path = public_path('uploads');
        if (!is_file($uploads_path . '/' . $img)) return ['code' => 202, 'msg' => '图片资源不存在'];
        $img_suffix = @mime_content_type($uploads_path . '/' . $img);
        if (substr_count($img_suffix, 'svg') == 0 && substr_count($img_suffix, 'plain') == 0) {
            return ['code' => 202, 'msg' => '图片资源格式不正确'];
        }
        return ['code' => 200, 'msg' => '格式正确'];
    }

    /**
     * 处理同建筑其他区域为非开始区域
     * @param $build_id int 所属建筑id
     * @param $except_id int 需要排除的id
     */
    public function checkIsStartData($build_id, $except_id = "")
    {
        $old_start_data = $this->where('is_start', 1)
            ->where('build_id', $build_id)
            ->where(function ($query) use ($except_id) {
                if (!$except_id) {
                    $query->where('id', '<>', $except_id);
                }
            })
            ->where('is_del', 1)
            ->pluck('id');
        $res = $this->whereIn('id', $old_start_data)->update(['is_start' => 2]);
        return $res;
    }
}
